<template>
  <div>
    <el-card>
      <CateGorySelect @getCategoryId="getCategoryId" :show="!isShoweTable"></CateGorySelect>
    </el-card>
    <el-card style="margin-top: 20px">
      <div v-show="isShoweTable">
        <el-button type="primary" icon="el-icon-plus" :disabled="!category3Id" @click="addAttr">添加属性</el-button>
        <!-- 表格 -->
        <el-table :data="attrList" style="width: 100%; margin-top: 15px" border>
          <el-table-column type="index" label="序号" width="80px" align="center"> </el-table-column>
          <el-table-column prop="attrName" label="属性名称" width="150px" align="center"> </el-table-column>
          <el-table-column prop="prop" label="属性值列表" width="width">
            <template v-slot="{ row }">
              <el-tag type="success" v-for="(attrValue, index) in row.attrValueList" :key="attrValue.id" style="margin-left: 10px">{{ attrValue.valueName }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="150px" align="center">
            <template v-slot="{ row, $index }">
              <el-button type="warning" icon="el-icon-edit" size="mini" @click="updataAttr(row)"></el-button>

              <el-popconfirm :title="`确定删除${row.attrName}吗？`" @onConfirm="deleteAttr(row, $index)">
                <el-button type="danger" icon="el-icon-delete" size="mini" slot="reference" style="margin-left: 10px"> </el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 添加属性/修改属性的结构 -->
      <div v-show="!isShoweTable">
        <el-form :inline="true" label-width="80px" :model="attrInfo">
          <el-form-item label="属性名">
            <el-input placeholder="请输入属性名" v-model="attrInfo.attrName"></el-input>
          </el-form-item>
        </el-form>
        <el-button type="primary" icon="el-icon-plus" @click="addAttrValue" :disabled="!attrInfo.attrName">添加属性值</el-button>
        <el-button type="" @click="isShoweTable = true">取消</el-button>
        <!-- 表格 -->
        <el-table :data="attrInfo.attrValueList" style="width: 100%; margin-top: 15px" border>
          <el-table-column type="index" label="序号" width="80px" align="center"> </el-table-column>
          <el-table-column prop="prop" label="属性值名称" width="width">
            <template v-slot="{ row, $index }">
              <!-- 切换显示和输入 -->
              <el-input v-model="row.valueName" placeholder="请输入属性值名称" size="mini" v-if="row.flag" :ref="$index" @blur="toLooKChange(row)" @keyup.native.enter="toLooKChange(row)"></el-input>
              <span v-else style="display: block" @click="editChange(row, $index)">{{ row.valueName }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="width">
            <template v-slot="{ row, $index }">
              <el-popconfirm :title="`确定删除${row.valueName}吗？`" @onConfirm="deleteAttrValue($index)">
                <el-button type="danger" icon="el-icon-delete" size="mini" slot="reference"></el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" style="margin-top: 15px" @click="addOrUpdateAttr" :disabled="attrInfo.attrValueList.length < 1">保存</el-button>
        <el-button type="" @click="isShoweTable = true" style="margin-top: 15px">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import cloneDeep from 'lodash/cloneDeep'
export default {
  data() {
    return {
      category1Id: '',
      category2Id: '',
      category3Id: '',
      attrList: [], //接受平台属性的数据
      isShoweTable: true, //显示table表格
      //收集添加。修改的属性
      attrInfo: {
        attrName: '', //属性名
        attrValueList: [],
        categoryId: 1, //三级分类的id
        categoryLevel: 3, //分类的级别
      },
    }
  },
  created() {},
  methods: {
    getCategoryId(form) {
      this.category1Id = form.category1Id
      this.category2Id = form.category2Id
      this.category3Id = form.category3Id
      if (this.category1Id && this.category2Id && this.category3Id) {
        this.getAttrList()
      }
    },
    async getAttrList() {
      let data = { category1Id: this.category1Id, category2Id: this.category2Id, category3Id: this.category3Id }
      let res = await this.$api.attribute.reqAttrList(data)
      if (res.code == 200) {
        this.attrList = res.data
      }
    },
    //添加属性值的处理函数
    addAttrValue() {
      this.attrInfo.attrValueList.push({
        attrId: this.attrInfo.id, //相应的属性id
        valueName: '',
        flag: true, //切换输入与显示
      })
      this.$nextTick(() => {
        //获取相应的input元素，自动聚焦
        this.$refs[this.attrInfo.attrValueList.length - 1].focus()
      })
    },
    //添加属性按钮的处理函数
    addAttr() {
      this.isShoweTable = false
      //清除数据
      this.attrInfo = {
        attrName: '', //属性名
        attrValueList: [],
        categoryId: this.category3Id, //三级分类的id
        categoryLevel: 3, //分类的级别
      }
    },
    //修改某个属性
    updataAttr(row) {
      //隐藏table
      this.isShoweTable = false
      //修改属性(因为是双向绑定且数据复杂所以要深拷贝)
      this.attrInfo = cloneDeep(row)
      //在修改某个属性的时候，将相应的属性值元素添加上flag
      this.attrInfo.attrValueList.forEach((item) => {
        this.$set(item, 'flag', false)
      })
    },
    // 失去焦点的处理函数  切换成显示模式
    toLooKChange(row) {
      //row：用户添加的新值(数组的最后一个元素)
      if (row.valueName.trim() === '') {
        this.$message({ message: '不能为空' })
        return
      }
      //新增的属性值不能与已有的属性值重复
      let isBoolean = this.attrInfo.attrValueList.some((item) => {
        // 将row从数组里面去除
        if (row !== item) {
          return item.valueName === row.valueName
        }
      })
      if (isBoolean) return
      row.flag = false
    },
    // 点击span的处理函数，变为编辑模式
    editChange(row, index) {
      row.flag = true
      this.$nextTick(() => {
        //获取相应的input元素，自动聚焦
        this.$refs[index].focus()
      })
    },
    // 气泡弹出框的确定函数
    deleteAttrValue(index) {
      // console.log(index)
      this.attrInfo.attrValueList.splice(index, 1)
    },
    //保存按钮，进行添加/修改的处理函数
    async addOrUpdateAttr() {
      // 如果用户添加了许多属性，需要检查属性是否为空，且提交给服务器的数据不应该出现flag属性
      this.attrInfo.attrValueList = this.attrInfo.attrValueList.filter((item) => {
        //过滤属性为空的
        if (item.valueName !== '') {
          //去除flag属性
          delete item.flag
          return true
        }
      })
      try {
        //发送保存请求
        let res = await this.$api.attribute.reqAddAttrOrUpdateAttr(this.attrInfo)
        // 隐藏添加属性的表格(展示展示属性的表格)
        this.isShoweTable = true
        if (res.code == 200) {
          this.$message({
            message: '恭喜你，修改成功',
            type: 'success',
          })
          this.getAttrList()
        }
      } catch (error) {
        this.$message.error('添加失败')
      }
    },
    //删除属性
    async deleteAttr(row, index) {
      try {
        //发送删除请求
        let res = await this.$api.attribute.reqDelete({ attrId: row.id })
        if (res.code == 200) {
          this.$message({
            message: '恭喜你，删除成功',
            type: 'success',
          })
          this.getAttrList()
        }
      } catch (error) {
        this.$message.error('删除失败')
      }
    },
  },
}
</script>

<style>
</style>